package com.senyint.imsdk.packet;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.jivesoftware.smack.packet.PacketExtension;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PacketReadExtension implements PacketExtension {
	public static final String TAG = PacketReadExtension.class.getSimpleName();
	
	public static final String NAMESPACE = "urn:syt:read" ;
	public static final String ELEMENT_NAME = "read" ;
    
    private String packetId ;
	
	public PacketReadExtension() {
	}
	
	public PacketReadExtension(String packetId ) {
		this.packetId = packetId ;
	}
	

	public String getPacketId() {
		return packetId;
	}

	@Override
	public String getElementName() {
		return ELEMENT_NAME;
	}
	
	@Override
	public String getNamespace() {
		return NAMESPACE;
	}
	
	@Override
	public String toXML() {
        StringBuffer sb = new StringBuffer();
        sb.append("<").append(ELEMENT_NAME).append(" xmlns=\"").append(NAMESPACE).append("\">");
        sb.append("<key>").append(packetId).append("</key>");
        sb.append("</"+ELEMENT_NAME+">");

        return sb.toString();
	}

    public static PacketReadExtension parse(String xml) {
        PacketReadExtension  pe = new PacketReadExtension();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();
            int size = nodeList.getLength();
            for (int i = 0; i < size; i++) {
                Node node = nodeList.item(i);
                String nodeName = node.getNodeName();
                String value = node.getTextContent();
                if (nodeName.equals("key")) {
                	pe.packetId = value;
                } 
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return pe;
    }
    
}
